import collections
from random import choice

Card = collections.namedtuple('Card', ['rank', 'suit'])


class FrenchDeck:
    ranks = [str(i) for i in range(2, 11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, position):
        return self._cards[position]


def spades_high(card: Card):
    suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
    rank_value = FrenchDeck.ranks.index(card.rank)
    return rank_value * len(suit_values) + suit_values[card.suit]


if __name__ == "__main__":
    deck = FrenchDeck()
    # 查看一副牌的长度
    print(len(deck))
    # 随机取一张牌
    print(choice(deck))
    # 取前三张牌
    print(deck[:3])
    # 取四张 A
    print(deck[12::13])
    # 迭代输出一副牌
    for card in deck:
        print(card)
    # 反向迭代输出一副牌
    for card in reversed(deck):
        print(card)
    # in运算符
    print(Card('3', 'spades') in deck)
    # 使用 spades_high 函数对这摞牌进行排序
    for card in sorted(deck, key=spades_high):
        print(card)
